In [2]:
from notebook.services.config import ConfigManager
from IPython.paths import locate_profile
cm = ConfigManager(profile_dir=locate_profile(get_ipython().profile))
cm.update('livereveal', {
'theme': 'league',
'transition': 'zoom',
'start_slideshow_at': 'selected',
})
Out[2]:
Input
First thing to note: If you want the user to be able to input their own information, you can use the input
function to store their result.
name = input("Please add your name: ")
print(name)
Create a variable that holds a value. Ask the user for input. If the input is > 20, multiple the two and print the result. Otherwise, divide the two and print it.
name_one = "Sarah"
name_two = "Rick"
name_three = "Morty"
Lists are mutable, which means you can change their content without changing how they are identified.
Immutable types, like strings, cannot be changed without the identity of the variable also changing.
The code would print ['cat', 'dog', 'hamster', 'narwhal']
, despite it being a different variable, all the references point to the same place!
In [36]:
movie_list = ['The Godfather', 'Jaws', 'Troy', 'Midnight Special', 'Casper']
In [37]:
# 0
print(movie_list[3])
movie_list[1] = "Toy Story"
print(len(movie_list))
In [38]:
# Python knows the size
print(movie_list[len(movie_list)])
In [39]:
print(len(movie_list))
# Why will this not work?
Lists in Python are zero-indexed. But if the len
function told us there were 4 elements (including 0), that would be confusing!
So, the length of a list may be 5 elements but we have to access them using zero-indexed indices. So, how would we get the last element?
In [40]:
print(movie_list[len(movie_list) - 1])
Using the method from the previous slides is pretty longwinded, although useful. This is the way to do it in most programming languages.
However, Python is not always like most programming languages. In this case, we have reverse indexing! Which works just how it sounds.
In [42]:
print(movie_list[-1]) #last element
print(movie_list[-2]) #second to last
The best way to think of negative indexing is to see:
list[-X]
as
list[len(list)-X]
house
In [1]:
three_elements = [1, 2, 3]
print(three_elements[0])
three_elements[0] = 'house'
print(three_elements)
empty_list = []
print(empty_list[1]) #IndexError
empty_list[0] = 1 #IndexError
In [2]:
dir([])
Out[2]:
In [4]:
awful_movies = []
awful_movies.append('The Artist')
awful_movies.append('The Room')
awful_movies.append('Rambo 4')
print(awful_movies)
In [17]:
great_movies = awful_movies.copy()
print(my_film.pop())
print(awful_movies)
#count('item_to_find')
print(awful_movies.index('Rambo 4'))
In [4]:
my_list = [1, 2, 3, 4, 5]
print("Length of list is: {0}".format(len(my_list)))
#for i in range(len(my_list)):
# print(i)
# print(my_list[i])
for jimmy in range(5):
print(jimmy)
In [12]:
my_list = ['cats', 'hippopotamus', 'weasel', 'glorbanflorb']
for index in range(len(my_list)):
print(index) # just the index
print('---------')
for key, value in enumerate(my_list):
print(key, value) #access both key and value
print('---------')
for value in my_list: #Called a For in or a For each loop
print(value) #access just value but NO index
# Is one better than the others?
As expected, there is no silver bullet
, each of these solutions is perfectly viable. However, when needing both index and value, enumerate
is recommended because it supports multiple data types.
There are many studies that show the memory usage and execution time of range
and enumerate
, but that is beyond the scope of this course.
In [16]:
cities = ['Manchester', 'Cardiff', 'London', 'Southampton']
for key,value in enumerate(cities):
print(value)
if 'h' in value:
print("H found at index: {0}".format(key))
In [17]:
nums = [31,45,12,300,40000,2]
total = 0
for num in nums:
total += num
print("Total is {0}".format(total))
print("Mean is {0}".format(total/len(nums)))
In [5]:
bad_words = ['fudge', 'bar steward', 'doody head']
my_string = input()
my_string_list = my_string.split(' ') #split at space to create a list of words
for word in my_string_list:
if word in bad_words:
print("Whoa now, no need for obscenities")
break
else:
print(word)
In [28]:
user_nums = []
total = 0
for i in range(0, 5):
user_input = input("Enter a positive integer please: ")
if user_input.isdigit():
user_nums.append(user_input)
total += int(user_input)
else:
print("I said POSITIVE NUMBER!")
break
if len(user_nums) == 5:
print(total/len(user_nums))
In [29]:
for i in range(0, 5):
if i == 2:
continue #head back to the top and go to the next value for i
print(i) #if i == 2 then this line is not executed
In [30]:
user_string = input()
vowels = ['a', 'e', 'i', 'o', 'u']
for letter in user_string:
if letter in vowels:
continue
print(letter)
In [31]:
def my_function():
In [32]:
def my_function():
pass
Lists in Python are more powerful than general arrays in most other languages. Lists allow you to perform comprehensions
, which are really just instructions that generally cover multiple lines, condensed down into a single line. For example, consider creating a list of all odd numbers between 1 and 100.
How might we do this?
In [3]:
odd_list = []
# for i in range(1, 100, 2):
# odd_list.append(i)
for i in range(1, 100):
if i % 2 != 0:
odd_list.append(i)
print(odd_list)
In [7]:
odd_list = [x for x in range(1, 100, 2)] # list comprehension is comprehensive!
print(odd_list)
In [33]:
i = 0
while(i < 6):
print(i)
i += 1
In [ ]:
i = 0
while(i < 10):
print(i) #how many times will i be printed?
HINT: CTRL-C ends a script
Sometimes, infinite loops can be useful. For example, we may want to keep receiving information from a client if we are listening for new files or input from a user if we are making a text-based game
In [ ]:
while(True):
user_string = input("Tell me a secret: ")
if user_string == "quit":
break
elif "dnp" in user_string:
continue
else:
print(user_string)
quit